package com.ny.controller;

import com.ny.entity.Classrooms;
import com.ny.entity.Reservations;
import com.ny.entity.Users;
import com.ny.service.ClassroomService;
import com.ny.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class ApplyController {
    @Autowired
    private ClassroomService classroomService;

    @Autowired
    private ReservationService reservationService;
//    跳转到申请界面
        @RequestMapping("/apply")
        public  String apply(){

            return "apply";
        }

//        申请功能：预约记录。添加一条预约记录。：
//    insert into reservations (user_id,classroom_id,start_datetime,...) values(#{user_id}....)
    @RequestMapping("/submitApply")
    public String submitApply(@RequestParam int classroomId,
                              @RequestParam int userId,
                              @RequestParam String startTime,
                              @RequestParam String endTime,
                              @RequestParam String reason) throws ParseException {
//        1.更新教室的状态，根据教室Id更新状态
        classroomService.updateClassroomStatusById(classroomId,"申请中");
//        2.预约表新增一条信息
        Reservations reservations = new Reservations();

        Users users = new Users();
        users.setUserId(userId);
        reservations.setUser(users);

        Classrooms classrooms = new Classrooms();
        classrooms.setClassroomId(classroomId);
        reservations.setClassroom(classrooms);
        //修改日期的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        reservations.setStartDatetime(sdf.parse(startTime));
        reservations.setEndDatetime(sdf.parse(endTime));
//        修改预约表的状态：申请中
        reservations.setStatus("申请中");
        reservations.setReason(reason);
        reservationService.addReservation(reservations);
        return "redirect:/classroomsList";
    }


}
